import { _decorator, Component, Node, AudioSource, Sprite, toDegree, Vec2, AudioClip } from 'cc';
import { Battle } from '../../Battle';
import { Enum_AudioClip } from '../../Enum';
import { Globals } from '../../Globals';
import { Player_Buttle } from '../../Player/Player_Buttle';
import { ResourcesUtil } from '../../ResourcesUtil';
import { EnemyController, EnemyFrameAnimType, EnemyFrameInfo } from '../Enemy/EnemyController';
import { EnemyFrameController } from '../Enemy/EnemyFrameController';
import { RoleFrame } from './RoleFrame';
const { ccclass, property } = _decorator;

@ccclass('RoleAttackTowerController')
export class RoleAttackTowerController extends Component {

    @property(Node)
    public bodyNode: Node = null;
    @property(Node)
    public animNode: Node = null;
    @property(Node)
    public gunNode: Node = null;
    @property(Number)
    public hurt: number = 10;

    public curAttackInterval: number = 1;
    public attackInterval: number = 1;
    public _audioSound: AudioSource;
    private arrow: AudioClip;
    // 速度
    public _speed: number = 1.5;
    // 移动方向
    public _moveDirection: number = 0;
    //是否在攻击
    public _isAttack: boolean = false;
    public _enemyFrameController: EnemyFrameController = null;
    public bodySprite: Sprite;
    public curAnimInfo: EnemyFrameInfo;
    // 攻击方向
    private _attackDirection: number = 0;

    private roleFrame: RoleFrame;
    private attackTarget: Node = null;

    async onLoad() {
        this.arrow = await ResourcesUtil.loadAudioClip(Enum_AudioClip.arrow);
    }

    onEnable(): void {
        this._audioSound = this.node.getComponent(AudioSource);
        this.bodySprite = this.animNode.getComponent(Sprite);
        // this.bodySprite.spriteFrame = null;
        if (this._enemyFrameController == null) {
            this._enemyFrameController = this.animNode.getComponent(EnemyFrameController);
            this._enemyFrameController.completeListener = this.OnCompleteListener.bind(this);
        }

        this._isAttack = false;
        this.roleFrame = this.node.getComponent(RoleFrame);
        this.PlayFrameAnim(EnemyFrameAnimType.Idle);
    }

    PlayFrameAnim(animType) {
        if (this.roleFrame) {
            this.roleFrame.PlayFrameAnim(animType);
        }
    }

    update(deltaTime: number) {
        if (!Battle.startGame) {
            return;
        }
        this.CalculateAttackDirection();
        if (this._isAttack) {
            this.curAttackInterval -= deltaTime;
            this.OnAttack(this.curAttackInterval);
        }
        else {
            this.curAttackInterval = 1;
            this.PlayFrameAnim(EnemyFrameAnimType.Idle);
        }
    }

    OnCompleteListener(animName) {
        this.curAttackInterval = 1;
        this.PlayFrameAnim(EnemyFrameAnimType.Idle);
    }

    OnAttack(interval: number) {
        if (interval <= 0) {
            this.curAttackInterval = 1;
            // console.log("播放攻击动画");
            this._audioSound.playOneShot(this.arrow);
            this.PlayFrameAnim(EnemyFrameAnimType.Attack);
            this.StartCreatePlayerBullet();
        }
    }

    CalculateAttackDirection() {
        this.attackTarget = this.getAttackTarget();
        if (this.attackTarget) {
            const y = this.attackTarget.getWorldPosition().y - this.node.getWorldPosition().y;
            const x = this.attackTarget.getWorldPosition().x - this.node.getWorldPosition().x;
            this._attackDirection = Math.atan2(y, x);
            this._isAttack = true;
            if (this.roleFrame) {
                this.roleFrame._isAttack = true;
            }
        }
        else {
            this.PlayFrameAnim(EnemyFrameAnimType.Idle);
            if (this.roleFrame) {
                this.roleFrame._isAttack = false;
            }
        }
    }

    /**
    * 创建player玩家子弹(普通攻击)
    *  */
    StartCreatePlayerBullet() {
        // console.log("创建子弹");
        if (this.attackTarget == null) {
            return;
        }
        // const muzzle = this.gunNode.getChildByName("muzzle");
        let angle = toDegree(this._attackDirection);
        const playerBulletNode = Globals.getNode("Player_Bullet", Battle.ContentParent);
        playerBulletNode.getComponent(Player_Buttle).hurt = 10;
        playerBulletNode.setWorldPosition(this.gunNode.getWorldPosition());//设置子弹初始点
        playerBulletNode.angle = angle; //设置子弹偏移角度，最近敌人的方向
        // 修改子弹节点Player_Buttle组件中的值
        playerBulletNode.getComponent(Player_Buttle).moveDirection = this._attackDirection;
        playerBulletNode.getComponent(Player_Buttle).isMoveing = true;
        // 改变角色方向
        if (this.attackTarget.getWorldPosition().x >= this.node.getWorldPosition().x) {
            this.bodyNode.setScale(1, 1);
        } else {
            this.bodyNode.setScale(-1, 1);
        }
    }

    /**
    * 攻击最近的敌人（获取最近敌人的方向）
    */
    getAttackTarget() {
        const Enemys = Battle.EnemyParent.children;
        const worldPos = this.node.getWorldPosition();
        let target: Node = null;
        let minDistance = 1000;
        let range = 480;
        for (let i = 0; i < Enemys.length; i++) {
            let enemyNode = Enemys[i];
            let result = false;
            let nodeName = enemyNode.name;
            if (nodeName.includes("Enemy") || nodeName.includes("Boss")) {
                let enemyCom = enemyNode.getComponent(EnemyController);
                if (!enemyCom.isDie) {
                    result = true;
                }
            }
            if (result) {
                const distance = Vec2.distance(enemyNode.getWorldPosition(), worldPos);
                if (distance <= minDistance && distance <= range) {
                    target = enemyNode;
                }
            }
        }
        return target;
    }
}


